<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\wh\builder\Admin;
use app\wh\builder\ZBuilder;
use app\mill\model\Client as ClientModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\wh\model\Color as ColorModel;
use app\wh\model\Material as MaterialModel;
use app\wh\model\Supplier as SupplierModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\Stock as StockModel;
use think\Db;
use think\facade\Env;

/**
 * 色号控制器
 * @package app\admin\controller
 */
class Color extends Admin
{

    //订单列表页
    public function order()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        cookie('__forward2__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        if(empty($map))$map[] = ['o.color_status','=',0];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,c.id as color_id')
            ->leftJoin('wh_order_color c','c.order_id=o.id')
            ->where(['o.status'=>1])
            ->where($map)
            ->group('o.id')
            ->order('c.id asc,o.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('确认颜色（工程数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['text:3', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'o.back', '内勤', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['batch','批次'],
                ['back','内勤'],
                ['color_status','状态','callback',function($value, $data){
                    $str = '未确认';
                    $value = intval($value);
                    if($value == 1)$str = '已确认';
                    $status = OrderModel::status_tag($value,$str);
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('colorSub',['title' => '取消定色','href' => url('colorSub'),'class'=>'btn btn-primary ajax-post confirm'])
            ->addRightButton('edit',['title' => '确认颜色','href' => url('edit',['order_id' => '__id__'])."",'class'=>'btn btn-primary','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }

    //确认颜色
    public function edit($id=null)
    {

        $id = input('param.id');
        $order_id = input('param.order_id');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            //如果无数据，则默认为不需要定色打样
            //反之，则记录数据
            if(!empty($data['color'])){
                //要校验的字段
                $validate = ['color'=>'请填写颜色名称','supplier_id'=>'请选择供应商','supplier_color'=>'请填写厂家色号','type_id'=>'请选择类别','heat'=>'请选择油温','color_type'=>'请填写油漆类型'];
                unset($validate['heat']);
                $lists = MaterialModel::serialize($data['color'],0,$validate);
                if(!is_array($lists))$this->error($lists);

                //合计确认颜色ID，删除多余的ID
                $color_ids = '';

                foreach ($lists as $sv){

                    $add_id = $sv['id'];
                    unset($sv['id']);

                    $sv['heat'] = intval($sv['heat']);
                    $sv['create_time'] = time();

                    //新增
                    if(empty($add_id))$add_id = Db::name('wh_order_color')->insertGetId($sv);
                    //更新
                    else Db::name('wh_order_color')->where(['id'=>$add_id])->update($sv);

                    //同步更新关联定色
                    ColorModel::addSameColor($add_id);

                    //合计确认颜色ID
                    $color_ids .= ",{$add_id}";
                }

                //删除多余的确认颜色ID
                if(!empty($lists[0]['order_id']))Db::name('wh_order_color')->where([['order_id','=',$lists[0]['order_id']],['id','not in',trim($color_ids,',')]])->delete();

            }

            Db::name('mill_order')->where(['id'=>$order_id])->update(['color_status'=>1]);

            //关闭子窗口，并刷新父窗口
            if(!empty(input('_pop')))$this->success('操作成功','','_parent_reload');
            $this->success('编辑成功', cookie('__forward2__'));
        }

        if(!empty($id))$order_id = Db::name('wh_order_color')->where(['id'=>$id])->value('order_id');
        if(empty($order_id))$this->error('该信息不存在');
        // 获取数据
        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();
        $order['supplier'] = SupplierModel::getGroup();

        $color_where = ['oc.order_id'=>$order_id,'oc.link_order_color_id'=>''];
        //$color_where = ['oc.order_id'=>$order_id];
        if(!empty($id))$color_where = ['oc.id'=>$id];
        $order['color'] = Db::name('wh_order_color')
            ->alias('oc')
            ->field('oc.*,oc.row_area as row_area2,oc.archives_number as archives_number2,oc.color_sn as color_sn2,s.title as supplier')
            ->leftJoin('wh_supplier s','s.id=oc.supplier_id')
            ->where($color_where)
            ->select();
        $order['type_plist'] = StockTypeModel::getGroup('',false,'id in ('.implode(',',ColorModel::$type_pid_arr).')');

        if(!empty($order['color'])){
            foreach ($order['color'] as &$v){
                $v['supplier_title'] = Db::name('wh_supplier')->where(['id'=>$v['supplier_id']])->value('title');
                $v['type_ptitle'] = Db::name('wh_stock_type')->where(['id'=>$v['type_pid']])->value('title');
                $v['type_title'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title');
                $v['type_title2'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id2']])->value('title');
                $v['type_title3'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id3']])->value('title');
                $v['color_type_title'] = Db::name('wh_supplier_color_type')->where(['id'=>$v['color_type_id']])->value('title');
                $v['heat_title'] = '';
                if(!empty($v['heat']))$v['heat_title'] = MaterialModel::$heat[$v['heat']];
            }
        }

        //查询是否有未确认的颜色
        $new_color_where = [];
        $archives_color = Db::name('wh_order_color')->alias('oc')->where($color_where)->column('archives_color');
        if(!empty($archives_color)){
            $new_color_where = [
                ['order_id','=',$order_id],
                ['color','not in',implode(',',$archives_color)],
            ];
        }
        elseif(empty($order['color'])){
            $new_color_where = [
                ['order_id','=',$order_id],
            ];
        }
        if(!empty($new_color_where)){
            $new_order_color = Db::name('mill_order_archives')
                ->field('id,color,order_id,archives_sn,sum(row_area) as row_area,sum(number) as archives_number')
                ->where($new_color_where)
                ->group('color')
                ->select();
        }

        //新增
        if(!empty($new_order_color)){
            foreach ($new_order_color as &$v){
                $v['stock_id'] = '';
                $v['stock_sn'] = '';
                $v['supplier_color'] = '';
                $v['color_sn'] = '';
                $v['supplier_id'] = '';
                $v['supplier_title'] = '';
                $v['type_pid'] = '';
                $v['type_ptitle'] = '';
                $v['type_id'] = '';
                $v['type_title'] = '';
                $v['type_id2'] = '';
                $v['type_title2'] = '';
                $v['type_id3'] = '';
                $v['type_title3'] = '';
                $v['heat'] = '';
                $v['heat_title'] = '';
                $v['color_type_id'] = '';
                $v['color_type_title'] = '';
                $v['color_sn'] = '';
                $v['archives_color'] = $v['color'];
                $v['row_area2'] = $v['row_area'];
                $v['archives_number2'] = $v['archives_number'];
                $v['color'] = '';
                $v['create_time'] = time();
                $v['id'] = '';
                $v['type_list'] = [];
            }

            $order['color'] = array_merge($order['color'],$new_order_color);
        }
        if(empty($order['color']))$this->error('请上传面积表');

        $table_arr = ColorModel::fromTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        //js
        $js = '<script type="text/javascript">

                $("input[name=\'show[color_sn][]\']").attr("placeholder","确认后自动生成");
                //禁用
                $(".disabled").attr("disabled","disabled");
                //删除
                function color_del(obj) {
                    var length = $(".color_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        //return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function color_add(obj) {
                    //var add = $(".color").parent().parent().html();
                    var add = $(obj).parents("tr").html();
                    add = "<tr>"+add+"</tr>";
                    
                    //$(add).insertAfter($(".color").parent("td").parent("tr:last"));
                    $(add).insertAfter($(obj).parents("tr"));
                    
                    $(obj).parents("tr").next().find("span.select2").remove();
                    $(obj).parents("tr").next().removeClass("hidden");
                    $(obj).parents("tr").next().find("input[name=\'color[id][]\']").val("");
                    $(obj).parents("tr").next().find("input[name=\'color[color_id][]\']").val("");
                    $(obj).parents("tr").next().find("input[name=\'color[color_sn][]\']").val("");
                    $(obj).parents("tr").next().find("input[name=\'color[color_sn2][]\']").val("");
                    
                    App.initHelpers(["select2"]);
                }
                //厂家色号，子窗口赋值
                function setSupplierColor(rel){
                    this.rel=rel;
                    //赋值处理
                    supplier_color_show(rel);
                }
                //厂家色号，子窗口获取值
                function getSupplierColor(){
                    return rel;
                }
                //打开厂家色号列表
                function supplier_color_list(obj) {
                    var color_obj = $(obj).prev("input[name=\'color[supplier_color][]\']");
                    //厂家色号
                    var color = color_obj.val();
                    //地址
                    //var href = $(obj).data("href")+"?_s=c.title="+color+"&_o=c.title=like";
                    var href = $(obj).data("href")+"?_s=c.model="+color+"&_o=c.model=like";
                    //当前点击事件的索引
                    var index = $("input[name=\'color[supplier_color][]\']").index(color_obj);
                    href = href.replace(/__parent_i__/,index);
                    $(obj).attr("href",href);
                }
                //查询厂家色号对应供应商
                function supplier_color_show(rel) {
                    var obj = $("input[name=\'color[supplier_color][]\']").eq(rel._parent_i);
                    
                    //查询厂家色号对应供应商
                    $.ajax({
                        url: \''.url("getSupplier").'?id=\'+rel.id,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        var supplier = data.supplier;
                        console.log(data);
                        
                        if(!data.supplier)Dolphin.notify("查询无该色号，请填写后续信息！", "danger");
                        else{
                            //Dolphin.notify("已有该厂家色号，请选择供应商！", "success");
                            
                            //自动填充
                            obj.val(supplier.model);
                            $(obj).parent().parent().find("input[name=\'color[stock_id][]\']").val(supplier.id);
                            $(obj).parent().parent().find("input[name=\'color[stock_sn][]\']").val(supplier.stock_sn);
                            
                            $(obj).parent().parent().find("input[name=\'color[color][]\']").val(supplier.title);
                            $(obj).parent().parent().find("input[name=\'show[color][]\']").val(supplier.title);
                            
                            $(obj).parent().parent().find("input[name=\'color[supplier_id][]\']").val(supplier.supplier_id);
                            $(obj).parent().parent().find("input[name=\'show[supplier_title][]\']").val(supplier.supplier_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[type_pid][]\']").val(supplier.type_pid);
                            $(obj).parent().parent().find("input[name=\'show[type_ptitle][]\']").val(supplier.type_ptitle);
                            
                            $(obj).parent().parent().find("input[name=\'color[type_id][]\']").val(supplier.type_id);
                            $(obj).parent().parent().find("input[name=\'show[type_title][]\']").val(supplier.type_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[type_id2][]\']").val(supplier.type_id2);
                            $(obj).parent().parent().find("input[name=\'show[type_title2][]\']").val(supplier.type_title2);
                            
                            $(obj).parent().parent().find("input[name=\'color[type_id3][]\']").val(supplier.type_id3);
                            $(obj).parent().parent().find("input[name=\'show[type_title3][]\']").val(supplier.type_title3);
                            
                            $(obj).parent().parent().find("input[name=\'color[heat][]\']").val(supplier.heat);
                            $(obj).parent().parent().find("input[name=\'show[heat_title][]\']").val(supplier.heat_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[color_type_id][]\']").val(supplier.color_type_id);
                            $(obj).parent().parent().find("input[name=\'show[color_type_title][]\']").val(supplier.color_type_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[color_sn][]\']").val(supplier.color_sn);
                            $(obj).parent().parent().find("input[name=\'show[color_sn][]\']").val(supplier.color_sn);
                            
                        }
                    });
                            
                }
            </script>';

        $info = $order;
        return ZBuilder::make('form')
            ->setPageTitle('确认颜色') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['select:12', 'hidden_supplier', '仅加载select插件用', '', $order['supplier'], '','','hidden'],
                ['complexTable:12', 'color', '', $table_data, $table_head],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            ->fetch();
    }
    public function edit_old($id=null)
    {

        $id = input('param.id');
        $order_id = input('param.order_id');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            //如果无数据，则默认为不需要定色打样
            //反之，则记录数据
            if(!empty($data['color'])){
                //要校验的字段
                $validate = ['color'=>'请填写颜色名称','supplier_id'=>'请选择供应商','supplier_color'=>'请填写厂家色号','type_id'=>'请选择类别','heat'=>'请选择油温','color_type'=>'请填写油漆类型'];
                unset($validate['heat']);
                $lists = MaterialModel::serialize($data['color'],0,$validate);
                if(!is_array($lists))$this->error($lists);

                foreach ($lists as $sv){

                    $add_id = $sv['id'];
                    unset($sv['id']);

                    $sv['heat'] = intval($sv['heat']);
                    $sv['create_time'] = time();

                    //新增
                    if(empty($add_id))Db::name('wh_order_color')->insert($sv);
                    //更新
                    else Db::name('wh_order_color')->where(['id'=>$add_id])->update($sv);

                    //更新采购单
                    //$goods_id = input('goods_id');
                    //if(!empty($goods_id)){
                    if(!empty($sv['color_id'])){
                        $goods_update = [
                            'material_name'     =>  $sv['color'],
                            'supplier_id'       =>  $sv['supplier_id'],
                            'model'             =>  $sv['supplier_color'],
                            'supplier_color'    =>  $sv['supplier_color'],
                            'type_pid'          =>  $sv['type_pid'],
                            'type_id'           =>  $sv['type_id'],
                            'heat'              =>  $sv['heat'],
                            'color_type_id'     =>  $sv['color_type_id'],
                            'color_sn'          =>  $sv['color_sn'],
                            'color_id'          =>  $sv['color_id'],
                        ];
                        Db::name('wh_material_goods')->where(['color_id'=>$sv['color_id']])->update($goods_update);
                    }
                }
            }

            Db::name('mill_order')->where(['id'=>$order_id])->update(['color_status'=>1]);

            //关闭子窗口，并刷新父窗口
            if(!empty(input('_pop')))$this->success('操作成功','','_parent_reload');
            $this->success('编辑成功', cookie('__forward__'));
        }

        if(!empty($id))$order_id = Db::name('wh_order_color')->where(['id'=>$id])->value('order_id');
        if(empty($order_id))$this->error('该信息不存在');
        // 获取数据
        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();
        $order['supplier'] = SupplierModel::getGroup();

        $color_where = ['oc.order_id'=>$order_id];
        if(!empty($id))$color_where = ['oc.id'=>$id];
        $order['color'] = Db::name('wh_order_color')
            ->alias('oc')
            ->field('oc.*,oc.row_area as row_area2,oc.archives_number as archives_number2,oc.color_sn as color_sn2,s.title as supplier')
            ->leftJoin('wh_supplier s','s.id=oc.supplier_id')
            ->where($color_where)
            ->select();
        $order['type_plist'] = StockTypeModel::getGroup('',false,'id in ('.implode(',',ColorModel::$type_pid_arr).')');

        //新增
        if(empty($order['color'])){
            $order['color'] = Db::name('mill_order_archives')
                ->field('id,color,order_id,archives_sn,sum(row_area) as row_area,sum(number) as archives_number')
                ->where(['order_id'=>$order_id])
                ->group('color')
                ->select();
            if(empty($order['color']))$this->error('请上传面积表');
            foreach ($order['color'] as &$v){
                $v['color_id'] = '';
                $v['supplier_color'] = '';
                $v['color_sn'] = '';
                $v['supplier_id'] = '';
                $v['supplier_title'] = '';
                $v['type_pid'] = '';
                $v['type_ptitle'] = '';
                $v['type_id'] = '';
                $v['type_title'] = '';
                $v['heat'] = '';
                $v['heat_title'] = '';
                $v['color_type_id'] = '';
                $v['color_type_title'] = '';
                $v['color_sn'] = '';
                $v['archives_color'] = $v['color'];
                $v['row_area2'] = $v['row_area'];
                $v['archives_number2'] = $v['archives_number'];
                $v['color'] = '';
                $v['create_time'] = time();
                $v['id'] = '';
                $v['type_list'] = [];
            }

        }
        else{
            foreach ($order['color'] as &$v){
                $v['supplier_title'] = Db::name('wh_supplier')->where(['id'=>$v['supplier_id']])->value('title');
                $v['type_ptitle'] = Db::name('wh_stock_type')->where(['id'=>$v['type_pid']])->value('title');
                $v['type_title'] = Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title');
                $v['color_type_title'] = Db::name('wh_supplier_color_type')->where(['id'=>$v['color_type_id']])->value('title');
                $v['heat_title'] = '';
                if(!empty($v['heat']))$v['heat_title'] = MaterialModel::$heat[$v['heat']];
            }
        }

        $table_arr = ColorModel::fromTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        //js
        $js = '<script type="text/javascript">

                $("input[name=\'show[color_sn][]\']").attr("placeholder","确认后自动生成");
                //禁用
                $(".disabled").attr("disabled","disabled");
                //删除
                function color_del(obj) {
                    var length = $(".color_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        //return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function color_add(obj) {
                    //var add = $(".color").parent().parent().html();
                    var add = $(obj).parents("tr").html();
                    add = "<tr>"+add+"</tr>";
                    
                    //$(add).insertAfter($(".color").parent("td").parent("tr:last"));
                    $(add).insertAfter($(obj).parents("tr"));
                    
                    $(obj).parents("tr").next().find("span.select2").remove();
                    $(obj).parents("tr").next().removeClass("hidden");
                    $(obj).parents("tr").next().find("input[name=\'color[color_id][]\']").val("");
                    $(obj).parents("tr").next().find("input[name=\'color[color_sn][]\']").val("");
                    $(obj).parents("tr").next().find("input[name=\'color[color_sn2][]\']").val("");
                    
                    App.initHelpers(["select2"]);
                }
                //厂家色号，子窗口赋值
                function setSupplierColor(rel){
                    this.rel=rel;
                    //赋值处理
                    supplier_color_show(rel);
                }
                //厂家色号，子窗口获取值
                function getSupplierColor(){
                    return rel;
                }
                //打开厂家色号列表
                function supplier_color_list(obj) {
                    var color_obj = $(obj).prev("input[name=\'color[supplier_color][]\']");
                    //厂家色号
                    var color = color_obj.val();
                    //地址
                    var href = $(obj).data("href")+"?_s=c.title="+color+"&_o=c.title=like";
                    //当前点击事件的索引
                    var index = $("input[name=\'color[supplier_color][]\']").index(color_obj);
                    href = href.replace(/__parent_i__/,index);
                    $(obj).attr("href",href);
                }
                //查询厂家色号对应供应商
                function supplier_color_show(rel) {
                    var obj = $("input[name=\'color[supplier_color][]\']").eq(rel._parent_i);
                    
                    //查询厂家色号对应供应商
                    $.ajax({
                        url: \''.url("getSupplier").'?id=\'+rel.id,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        var supplier = data.supplier;
                        console.log(data);
                        
                        if(!data.supplier)Dolphin.notify("查询无该色号，请填写后续信息！", "danger");
                        else{
                            //Dolphin.notify("已有该厂家色号，请选择供应商！", "success");
                            
                            //自动填充
                            obj.val(supplier.title);
                            $(obj).parent().parent().find("input[name=\'color[color_id][]\']").val(supplier.color_id);
                            
                            $(obj).parent().parent().find("input[name=\'color[color][]\']").val(supplier.color_title);
                            $(obj).parent().parent().find("input[name=\'show[color][]\']").val(supplier.color_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[supplier_id][]\']").val(supplier.supplier_id);
                            $(obj).parent().parent().find("input[name=\'show[supplier_title][]\']").val(supplier.supplier_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[type_pid][]\']").val(supplier.type_pid);
                            $(obj).parent().parent().find("input[name=\'show[type_ptitle][]\']").val(supplier.type_ptitle);
                            
                            $(obj).parent().parent().find("input[name=\'color[type_id][]\']").val(supplier.type_id);
                            $(obj).parent().parent().find("input[name=\'show[type_title][]\']").val(supplier.type_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[heat][]\']").val(supplier.heat);
                            $(obj).parent().parent().find("input[name=\'show[heat_title][]\']").val(supplier.heat_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[color_type_id][]\']").val(supplier.color_type_id);
                            $(obj).parent().parent().find("input[name=\'show[color_type_title][]\']").val(supplier.color_type_title);
                            
                            $(obj).parent().parent().find("input[name=\'color[color_sn][]\']").val(supplier.color_sn);
                            $(obj).parent().parent().find("input[name=\'show[color_sn][]\']").val(supplier.color_sn);
                            
                        }
                    });
                            
                }
            </script>';

        $info = $order;
        return ZBuilder::make('form')
            ->setPageTitle('确认颜色') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['select:12', 'hidden_supplier', '仅加载select插件用', '', $order['supplier'], '','','hidden'],
                ['complexTable:12', 'color', '', $table_data, $table_head],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            ->fetch();
    }

    //根据厂家色号查找对应供应商
    public function getSupplier(){

        $id = input('id');
        $color = input('color');
        $supplier_id = input('supplier_id');

        //过滤颜色特殊字符
        $color = strtoupper(trim($color));
        $where = [];
        if($id)$where[] = ['c.id','=',$id];
        if($color)$where[] = ['c.model','=',$color];
        if($supplier_id)$where[] = ['s.id','=',$supplier_id];

        $data = Db::name('wh_stock')
            ->alias('c')
            ->field('c.*,s.id as supplier_id,s.title as supplier_title,st.title as type_title,st2.title as type_title2,st3.title as type_title3,stt.title as type_ptitle,ct.title as color_type_title')
            ->leftJoin('wh_supplier s','s.id=c.supplier_id')
            ->leftJoin('wh_stock_type st','st.id=c.type_id')
            ->leftJoin('wh_stock_type st2','st2.id=c.type_id2')
            ->leftJoin('wh_stock_type st3','st3.id=c.type_id3')
            ->leftJoin('wh_stock_type stt','stt.id=c.type_pid')
            ->leftJoin('wh_supplier_color_type ct','ct.id=c.color_type_id')
            ->where($where)
            ->find();

        //油温
        if(!empty($data['heat']))$data['heat_title'] = MaterialModel::$heat[$data['heat']];

        echo json_encode(['supplier'=>$data],JSON_UNESCAPED_UNICODE);exit;
    }

    //AJAX类别列表
    public function getStockType(){
        $list = [];
        $color_arr = input('color');
        $pid = input('type_pid',input('type_id',input('type_id2')));
        if(!empty($color_arr['type_pid']))$pid = reset($color_arr['type_pid']);
        if(!empty($pid))$list = StockTypeModel::getAjaxGroup($pid);
        echo json_encode(['code'=>1,'msg'=>'操作成功','list'=>$list]);
    }

    //根据厂家色号查找对应供应商
    public function supplierColorList(){

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $_parent_i = input('_parent_i');
        $color = input('color');
        $type_pid = input('type_pid');
        $supplier_id = input('supplier_id');

        $map = $this->getMap();
        if(!empty($map)){
            foreach ($map as $m){
                //过滤颜色特殊字符
                if($m[0] == 'c.model'){
                    $m[2] = trim($m[2]);
                    $color = trim($m[2],"%");
                }
                if($m[0] == 'c.supplier_id')$supplier_id = trim($m[2]);
                if($m[0] == 'c.type_pid')$type_pid = trim($m[2]);
                if($m[0] == 'c.type_id')$type_id = trim($m[2]);
            }
        }
        if($supplier_id)$map[] = ['s.id','=',$supplier_id];
        $map[] = ['c.type_pid','in',implode(',',ColorModel::$type_pid_c_arr)];
        $map = array_merge($map);

        //设置新增厂家色号的缓存
        $add_session = [
            'title'                 =>  urldecode(input('_parent_color_title')),
            'model'                 =>  !empty($color)?strtoupper(trim($color)):'',
            'supplier_color'        =>  !empty($color)?strtoupper(trim($color)):'',
            'supplier_id'           =>  !empty($supplier_id)?$supplier_id:'',
            'type_pid'              =>  !empty($type_pid)?$type_pid:'',
            'type_id'               =>  !empty($type_id)?$type_id:'',
        ];
        session('_supplier_color_add_',$add_session);

        $data_list = Db::name('wh_stock')
            ->alias('c')
            ->field('c.*,s.id as supplier_id,s.title as supplier_title,st.title as type_title,st2.title as type_title2,st3.title as type_title3,stt.title as type_ptitle,ct.title as color_type_title')
            ->leftJoin('wh_supplier s','s.id=c.supplier_id')
            ->leftJoin('wh_stock_type st','st.id=c.type_id')
            ->leftJoin('wh_stock_type st2','st2.id=c.type_id2')
            ->leftJoin('wh_stock_type st3','st3.id=c.type_id3')
            ->leftJoin('wh_stock_type stt','stt.id=c.type_pid')
            ->leftJoin('wh_supplier_color_type ct','ct.id=c.color_type_id')
            ->where($map)
            ->select();

        if(!empty($data_list)){
            foreach ($data_list as &$v){
                if(!empty($v['heat']))$v['heat_title'] = MaterialModel::$heat[$v['heat']];

                //获取关联的物料类型库存
                $new_stock_sn = StockModel::addSameStock($v['stock_sn']);
                if(!empty($new_stock_sn)){
                    $new_stock = Db::name('wh_stock')->where(['stock_sn'=>$new_stock_sn])->find();
                    $new_stock['type_ptitle'] = Db::name('wh_stock_type')->where(['id'=>$new_stock['type_pid']])->value('title');
                    $v['number'] = "{$v['type_ptitle']}：{$v['number']}<br>{$new_stock['type_ptitle']}：{$new_stock['number']}";
                }
            }

        }

        $supplier_where = '(';
        foreach (ColorModel::$type_pid_c_arr as $tpkey=>$tpid){
            if($tpkey > 0)$supplier_where .= " or ";
            $supplier_where .= " find_in_set({$tpid},`type_pid`)";
        }
        $supplier_where .= ')';
        $supplier = Db::name('wh_supplier')->where($supplier_where)->column('title','id');
        $type_where = 'id in ('.implode(',',ColorModel::$type_pid_c_arr).')';
        $type_plist = Db::name('wh_stock_type')->where($type_where)->column('title','id');
        $type_list = [];
        if(!empty($type_pid))$type_list = StockTypeModel::getGroup($type_pid);

        //JS
        $js = '<script type="text/javascript">
            $(function(){
                //选择厂家色号，并传值给父窗口
                $("body").on(\'click\',"input[name=\'ids[]\']", function(){
                    //父窗口索引
                    var _parent_i = '.$_parent_i.';
                    //厂家色号ID
                    var id = $(this).val();
                    //传递给父窗口的值
                    var arr = {
                        _parent_i:_parent_i,
                        id:id
                    };
                    //子窗口索引
                    var index = parent.layer.getFrameIndex(window.name);
                    //向父窗口传值
                    parent.setSupplierColor(arr);
                    //关闭子窗口
                    parent.layer.close(index);
                });
                
                // 搜索点击事件，自动搜索
                $("#search-area").change(function(){
                    $(this).find("button[type=\'submit\']").click();
                });
                $("#search-area").bind("input propertychange",function(){
                    $(this).find("button[type=\'submit\']").click();
                });
            });
        </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('厂家色号') // 页面标题
            ->setTableName('wh_stock') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'c.model', '厂家色号', 'like'],
                ['select:2', 'c.supplier_id', '供应商', '', '',$supplier],
                ['select:1', 'c.type_pid', '油漆类别', '', '',$type_plist],
                ['select:1', 'c.type_id', '类别', '', '',$type_list],
            ])
            ->addColumns([ // 批量添加列
                ['model', '厂商色号'],
                ['title', '颜色名称'],
                ['number', '库存'],
                ['supplier_title', '供应商'],
                ['type_ptitle','油漆类别'],
                ['type_title','类别'],
                ['type_title2','类别2'],
                ['type_title3','类别3'],
                ['heat_title','油温'],
                ['color_type_id','油漆类型','','',ColorModel::getColorType()],
                ['color_sn','自编码'],
                //['right_button', '操作', 'btn']
            ])
            ->addTopButton('supplierColorAdd',['title' => '新增','href' => url('supplierColorAdd',['_pop'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['800px', '90%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('supplierColorAdd',['title' => '编辑','href' => url('supplierColorAdd',['id' => '__id__'])."",'class'=>'btn btn-primary'])
            ->setRowList($data_list) // 设置表格数据
            ->setExtraJs($js)
            ->setColumnWidth([
                'id'  => 60,
                'model'  => 150,
                'sum_number'  => 80,
                'title'  => 150,
                'supplier_title'  => 150,
                'type_ptitle'  => 60,
                'type_title'  => 60,
                'type_title2'  => 60,
                'type_title3'  => 60,
                'heat'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    public function supplierColorList_old(){

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $_parent_i = input('_parent_i');
        $color = input('color');
        $type_pid = input('type_pid');
        $supplier_id = input('supplier_id');

        $map = $this->getMap();
        if(!empty($map)){
            foreach ($map as $m){
                //过滤颜色特殊字符
                if($m[0] == 'c.title'){
                    $m[2] = trim($m[2]);
                    $color = trim($m[2],"%");
                }
                if($m[0] == 'c.supplier_id')$supplier_id = trim($m[2]);
                if($m[0] == 'c.type_pid')$type_pid = trim($m[2]);
                if($m[0] == 'c.type_id')$type_id = trim($m[2]);
            }
        }
        if($supplier_id)$map[] = ['s.id','=',$supplier_id];

        //设置新增厂家色号的缓存
        $add_session = [
            'color_title'           =>  urldecode(input('_parent_color_title')),
            'title'                 =>  !empty($color)?strtoupper(trim($color)):'',
            'supplier_id'           =>  !empty($supplier_id)?$supplier_id:'',
            'type_pid'              =>  !empty($type_pid)?$type_pid:'',
            'type_id'               =>  !empty($type_id)?$type_id:'',
        ];
        session('_supplier_color_add_',$add_session);

        $data_list = Db::name('wh_supplier_color')
            ->alias('c')
            ->field('c.*,c.id as color_id,s.id as supplier_id,s.title as supplier_title,st.title as type_title,stt.title as type_ptitle,ct.title as color_type_title')
            ->leftJoin('wh_supplier s','s.id=c.supplier_id')
            ->leftJoin('wh_stock_type st','st.id=c.type_id')
            ->leftJoin('wh_stock_type stt','stt.id=c.type_pid')
            ->leftJoin('wh_supplier_color_type ct','ct.id=c.color_type_id')
            ->where($map)
            ->select();

        if(!empty($data_list)){
            foreach ($data_list as &$v){
                if(!empty($v['heat']))$v['heat_title'] = MaterialModel::$heat[$v['heat']];
                //获取库存
                $v['sum_number'] = ColorModel::getSupplierColorNum($v['id']);
            }

        }

        $supplier_where = '(';
        foreach (ColorModel::$type_pid_arr as $tpkey=>$tpid){
            if($tpkey > 0)$supplier_where .= " or ";
            $supplier_where .= " find_in_set({$tpid},`type_pid`)";
        }
        $supplier_where .= ')';
        $supplier = Db::name('wh_supplier')->where($supplier_where)->column('title','id');
        $type_where = 'id in ('.implode(',',ColorModel::$type_pid_arr).')';
        $type_plist = Db::name('wh_stock_type')->where($type_where)->column('title','id');
        $type_list = [];
        if(!empty($type_pid))$type_list = StockTypeModel::getGroup($type_pid);

        //JS
        $js = '<script type="text/javascript">
            $(function(){
                //选择厂家色号，并传值给父窗口
                $("body").on(\'click\',"input[name=\'ids[]\']", function(){
                    //父窗口索引
                    var _parent_i = '.$_parent_i.';
                    //厂家色号ID
                    var id = $(this).val();
                    //传递给父窗口的值
                    var arr = {
                        _parent_i:_parent_i,
                        id:id
                    };
                    //子窗口索引
                    var index = parent.layer.getFrameIndex(window.name);
                    //向父窗口传值
                    parent.setSupplierColor(arr);
                    //关闭子窗口
                    parent.layer.close(index);
                });
                
                // 搜索点击事件，自动搜索
                $("#search-area").change(function(){
                    $(this).find("button[type=\'submit\']").click();
                });
                $("#search-area").bind("input propertychange",function(){
                    $(this).find("button[type=\'submit\']").click();
                });
            });
        </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('厂家色号') // 页面标题
            ->setTableName('wh_supplier_color') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'c.title', '厂家色号', 'like'],
                ['select:2', 'c.supplier_id', '供应商', '', '',$supplier],
                ['select:1', 'c.type_pid', '油漆类别', '', '',$type_plist],
                ['select:1', 'c.type_id', '类别', '', '',$type_list],
            ])
            ->addColumns([ // 批量添加列
                ['title', '厂商色号'],
                ['color_title', '颜色名称'],
                ['sum_number', '库存'],
                ['supplier_title', '供应商'],
                ['type_ptitle','油漆类别'],
                ['type_title','类别'],
                ['heat_title','油温'],
                ['color_type_id','油漆类型','','',ColorModel::getColorType()],
                ['color_sn','自编码'],
                //['right_button', '操作', 'btn']
            ])
            ->addTopButton('supplierColorAdd',['title' => '新增','href' => url('supplierColorAdd',['_pop'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['800px', '90%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('supplierColorAdd',['title' => '编辑','href' => url('supplierColorAdd',['id' => '__id__'])."",'class'=>'btn btn-primary'])
            ->setRowList($data_list) // 设置表格数据
            ->setExtraJs($js)
            ->setColumnWidth([
                'id'  => 60,
                'title'  => 150,
                'sum_number'  => 80,
                'color_title'  => 150,
                'supplier_title'  => 150,
                'type_ptitle'  => 60,
                'type_title'  => 60,
                'heat'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    //新增厂家色号
    public function supplierColorAdd(){

        $id = input('id');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();
            $data['model'] = strtoupper(trim($data['model']));
            $data['title'] = trim($data['title']);
            // 验证
            $result = $this->validate($data, 'Suppliercolor');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            if($id)$info = Db::name('wh_stock')->where(['id'=>$id])->find();

            $data['supplier_color'] = $data['model'];
            //判断是否已录入
            $in_sn = StockModel::getStockSn($data,false);

            if(!empty($in_sn)){
                if($id){
                    if($info['stock_sn'] != $in_sn)$this->error('该色号已存在');
                }
                else $this->error('该色号已存在');

            }

            if(empty($data['id'])){

                $data['color_sn'] = ColorModel::getColorSn($data['type_id'],$data['heat']);
                $re = StockModel::getStockSn($data);
            }
            else $re = StockModel::update($data);

            //同步新增同规格不同物料类别的库存
            $stock_sn = StockModel::getStockSn($data);
            StockModel::addSameStock($stock_sn,$info);

            $this->success('操作成功', cookie('__forward__'),'_parent_reload');
        }

        $info = Db::name('wh_stock')->where(['id'=>$id])->find();
        $add_session = session('_supplier_color_add_');
        if(empty($info))$info = $add_session;

        $supplier_where = '(';
        foreach (ColorModel::$type_pid_arr as $tpkey=>$tpid){
            if($tpkey > 0)$supplier_where .= " or ";
            $supplier_where .= " find_in_set({$tpid},`type_pid`)";
        }
        $supplier_where .= ')';
        $supplier = Db::name('wh_supplier')->where($supplier_where)->column('title','id');
        $type_where = 'id in ('.implode(',',ColorModel::$type_pid_arr).')';
        $type_plist = Db::name('wh_stock_type')->where($type_where)->column('title','id');
        $type_list = [];
        if(!empty($info['type_id']))$type_list = StockTypeModel::getGroup($info['type_pid']);
        $type_list2 = [];
        if(!empty($info['type_id2']))$type_list2 = StockTypeModel::getGroup($info['type_id']);
        $type_list3 = [];
        if(!empty($info['type_id3']))$type_list3 = StockTypeModel::getGroup($info['type_id2']);

        return ZBuilder::make('form')
            ->setPageTitle('新增厂家色号') // 页面标题
            ->addHidden('model')
            ->addFormItems([ // 批量添加表单项
                ['text:12||||must', 'model', '厂家色号'],
                ['text:12||||must', 'title', '颜色名称'],
                ['select:12||||must', 'supplier_id', '供应商','',$supplier],
                ['linkage:12||||must', 'type_pid', '物料类别', '', $type_plist,'', url('getStockType'), 'type_id'],
                ['linkage:12||||must', 'type_id', '类别', '', $type_list,'', url('getStockType'), 'type_id2'],
                ['linkage:12||||must', 'type_id2', '类别2', '', $type_list2,'', url('getStockType'), 'type_id3'],
                ['select:12||||must', 'type_id3', '类别3', '', $type_list3],
                ['select:12||||must', 'heat', '油温', '', MaterialModel::$heat,''],
                ['select:12||||must', 'color_type_id', '油漆类型', '', ColorModel::getColorType(),''],
            ])
            ->setFormData($info)
            ->fetch();
    }
    public function supplierColorAdd_old(){

        $id = input('id');

        if ($this->request->isPost()) {
            $data = input();
            $data['title'] = strtoupper(trim($data['title']));
            $data['color_title'] = trim($data['color_title']);
            // 验证
            $result = $this->validate($data, 'Suppliercolor');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            //判断厂家色号是否已录入
            $where = [
                'title'             =>  $data['title'],
                'supplier_id'       =>  $data['supplier_id'],
                'type_id'           =>  $data['type_id'],
            ];
            $is_count = Db::name('wh_supplier_color')->where($where)->count();
            if(!empty($is_count))$this->error('该色号已存在');

            if(empty($id)){
                $data['create_time'] = time();
                $data['color_sn'] = ColorModel::getColorSn($data['type_id'],$data['heat']);

                Db::name('wh_supplier_color')->insert($data);
            }
            else Db::name('wh_supplier_color')->where(['id'=>$id])->update($data);

            $this->success('操作成功', cookie('__forward__'),'_parent_reload');
        }

        $info = Db::name('wh_supplier_color')->where(['id'=>$id])->find();
        $add_session = session('_supplier_color_add_');
        if(empty($info))$info = $add_session;

        $supplier_where = '(';
        foreach (ColorModel::$type_pid_arr as $tpkey=>$tpid){
            if($tpkey > 0)$supplier_where .= " or ";
            $supplier_where .= " find_in_set({$tpid},`type_pid`)";
        }
        $supplier_where .= ')';
        $supplier = Db::name('wh_supplier')->where($supplier_where)->column('title','id');
        $type_where = 'id in ('.implode(',',ColorModel::$type_pid_arr).')';
        $type_plist = Db::name('wh_stock_type')->where($type_where)->column('title','id');
        $type_list = [];
        if(!empty($info['type_id']))$type_list = StockTypeModel::getGroup($info['type_pid']);

        return ZBuilder::make('form')
            ->setPageTitle('新增厂家色号') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['text:12||||must', 'title', '厂家色号'],
                ['text:12||||must', 'color_title', '颜色名称'],
                ['select:12||||must', 'supplier_id', '供应商','',$supplier],
                ['linkage:12||||must', 'type_pid', '物料类别', '', $type_plist,'', url('getStockType'), 'type_id'],
                ['select:12||||must', 'type_id', '类别', '', $type_list],
                ['select:12||||must', 'heat', '油温', '', MaterialModel::$heat,''],
                ['select:12||||must', 'color_type_id', '油漆类型', '', ColorModel::getColorType(),''],
            ])
            ->setFormData($info)
            ->fetch();
    }

    //采购定量
    public function ration()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        if(empty($map))$map[] = ['c.status','=',0];
        // 数据列表
        $data_list = Db::name('wh_order_color')
            ->alias('c')
            ->field('c.*,o.archives_sn,o.engineering,sc.number as sum_number,s.title as supplier')
            ->leftJoin('mill_order o','c.order_id=o.id')
            ->leftJoin('wh_stock sc','c.stock_id=sc.id')
            ->leftJoin('wh_supplier s','c.supplier_id=s.id')
            ->where($map)
            ->order('c.id asc,o.archives_sn')
            ->paginate()
            ->each(function ($v){

                //总面积换算成采购量
                $v['row_area'] = ColorModel::areaToKg($v['row_area']);

                return $v;
            })
        ;

        //js
        $js = '
            <script type="text/javascript">
                jQuery.fn.rowspan = function(colIdx=0) {
                    var that;
                    return this.each(function(row) {
                        $("td:eq(" + colIdx + ")", this).filter(":visible").each(function(col) {
                            if (that != null && $(this).html() == $(that).html()) {
                                rowspan = $(that).attr("rowSpan");
                                if (rowspan == undefined) {
                                    $(that).attr("rowSpan", 1);
                                    rowspan = $(that).attr("rowSpan");
                                }
                                rowspan = Number(rowspan) + 1;
                                $(that).attr("rowSpan", rowspan);
                                $(this).hide();
                            } else {
                                that = this;
                            }
                        });
                        
                    
                    });
                };
                $(function() {
                    //要合并的列序号，后面数字是第几列
                    $("#builder-table-main").find("tr").rowspan(0);
                    $("#builder-table-main").find("tr").rowspan(1);
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('确认颜色（工程数量'.$data_list->total().'）') // 页面标题
            ->setTableName('wh_order_color') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['text:3', 'o.engineering', '工程名称', 'like'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['supplier_color','厂家色号'],
                ['color_sn','自编码'],
                ['supplier','供应商'],
                ['color','颜色'],
                ['sum_number','库存(kg)'],
                ['row_area','面积(M²)'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('rationSubs',['title' => '取消定量','href' => url('rationSubs'),'class'=>'btn btn-primary ajax-post confirm'])
            ->addRightButton('ration',['title' => '定量','href' => url('rationSub',['id' => '__id__']),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '80%'], 'title' => ['确认定量', 'font-size:24px;text-align: center;']])
            ->addRightButton('modelShow',['title' => '版型查看','href' => url('modelShow',['id' => '__id__']),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '100%'], 'title' => ['版型查看', 'font-size:24px;text-align: center;']])
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }

    //确认定量
    public function rationSub(){

        $id = input('id');

        if ($this->request->isPost()){
            $data = $this->request->post();

            $update = ['status'=>1];
            if(!empty($data['number']))$update['number'] = $data['number'];

            if(!(Db::name('wh_order_color')->where(['id'=>$id])->update($update)))$this->error('操作失败');

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $map[] = ['c.id','=',$id];
        // 获取数据
        $info = Db::name('wh_order_color')
            ->alias('c')
            ->field('c.*,o.archives_sn,o.engineering,sc.number as sum_number,s.title as supplier')
            ->leftJoin('mill_order o','c.order_id=o.id')
            ->leftJoin('wh_stock sc','c.stock_id=sc.id')
            ->leftJoin('wh_supplier s','c.supplier_id=s.id')
            ->where($map)
            ->find();
        $info['engineering'] = "{$info['engineering']}  {$info['archives_sn']}";
        //总面积换算成采购量
        //$info['row_area'] = ColorModel::areaToKg($info['row_area']);

        //计算需要采购多少
        $info['buy_number'] = 0;
        if(empty($info['number'])){
            //$info['number'] = '';
            //$info['buy_number'] = floatval($info['sum_number'])-$info['row_area'];
            //if($info['buy_number'] < 0)$info['number'] = abs($info['buy_number']);
        }

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    var number = $("input[name=buy_number]").val();
                    if(number > 0){
                        $("input[name=number]").attr("placeholder","库存充足不需要采购");
                        $("input[name=number]").attr("disabled","disabled");
                    }
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('确认定量') // 页面标题
            ->addHidden('buy_number')
            ->addStatic('engineering', '工程名称')
            ->addStatic('supplier_color', '厂家色号')
            ->addStatic('supplier', '供应商')
            ->addStatic('color_sn', '自编码')
            ->addStatic('color', '颜色')
            ->addStatic('sum_number', '库存(kg)')
            ->addStatic('row_area', '面积(M²)')
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'number', '实际采购量'],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            ->layout(['engineering'=>12,'number'=>12])
            ->fetch();

    }

    //版型查看
    public function modelShow(){

        $id = input('id');
        $map[] = ['c.id','=',$id];
        // 获取数据
        $info = Db::name('wh_order_color')
            ->alias('c')
            ->field('c.*,o.archives_sn,o.engineering,sc.number as sum_number,s.title as supplier')
            ->leftJoin('mill_order o','c.order_id=o.id')
            ->leftJoin('wh_stock sc','c.stock_id=sc.id')
            ->leftJoin('wh_supplier s','c.supplier_id=s.id')
            ->where($map)
            ->find();
        $info['engineering'] = "{$info['engineering']}  {$info['archives_sn']}";

        $table_group_head = [['厚度','颜色','铝板版型','合计件数','合计面积',]];
        $group_where = [
            ['order_id','=',$info['order_id']],
            ['color','=',$info['archives_color']],
        ];
        //$id = null,$fields = '',$order = 'sort asc',$group = '',$join = [],$where = []
        $table_group_data = ArchivesModel::getList('','thickness,color,model,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','thickness,color,model',[],$group_where);

        $hideBtn = ['submit'];

        return ZBuilder::make('form')
            ->setPageTitle('版型查看') // 页面标题
            ->addStatic('engineering', '工程名称')
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'list_archives_group', '', $table_group_data, $table_group_head],
            ])
            ->setFormData($info)
            ->layout(['archives_drawing'=>12])
            ->hideBtn($hideBtn)
            ->fetch();

    }

    //确认颜色  批量
    public function colorSub(){
        $ids = input('ids');
        $ids = implode(',',$ids);

        Db::name('mill_order')->where([['id','in',$ids]])->update(['color_status'=>1]);

        $this->success('操作成功');
    }

    //确认定量  批量
    public function rationSubs(){
        $ids = input('ids');
        $ids = is_array($ids)?implode(',',$ids):$ids;

        $order_ids = input('order_ids');
        $order_ids = is_array($order_ids)?implode(',',$order_ids):$order_ids;

        $where = [];
        if(!empty($ids))$where[] = ['id','in',$ids];
        if(!empty($order_ids))$where[] = ['order_id','in',$order_ids];

        Db::name('wh_order_color')->where($where)->update(['status'=>2]);

        $this->success('操作成功');
    }

    //油漆类型
    public function colorType(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('wh_supplier_color_type')->where($map)->order('id desc')->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('油漆类型') // 页面标题
            ->setTableName('wh_supplier_color_type') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['title', '油漆类型'],
                //['note', '备注'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增','href' => url('colorTypeAdd'),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '65%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit',['title' => '修改','href' => url('colorTypeAdd',['id' => '__id__']),'icon'=>''],['area' => ['780px', '65%'], 'title' => ['修改', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'status'  => 60,
            ])
            ->fetch(); // 渲染模板
    }

    //新增油漆类型
    public function colorTypeAdd()
    {

        $id = input('param.id');
        // 获取数据
        $info = Db::name('wh_supplier_color_type')->where(['id'=>$id])->find();

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');

            // 验证失败 输出错误信息
            if(empty($data['title'])) $this->error('油漆类型不能为空');

            if($id)$re = Db::name('wh_supplier_color_type')->where(['id'=>$id])->update($data);
            else $re = Db::name('wh_supplier_color_type')->insert($data);

            if ($re)$this->success('操作成功','','_parent_reload');
            else $this->error('操作失败');
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增')
            ->addFormItems([
                ['text:12||||must', 'title', '油漆类型'],
            ])
            ->setFormData($info)
            //->layout(['title'=>12,'sort'=>12,])
            ->fetch();
    }

    //铝卷材质类型
    public function quality($type_pid = 4){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['type_pid','=',$type_pid];
        // 数据列表
        $data_list = Db::name('wh_supplier_quality')->where($map)->order('id desc')->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('材质类型') // 页面标题
            ->setTableName('wh_supplier_quality') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['title', '材质类型'],
                //['note', '备注'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增','href' => url('qualityAdd',['type_pid'=>$type_pid]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '65%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit',['title' => '修改','href' => url('qualityAdd',['id' => '__id__']),'icon'=>''],['area' => ['780px', '65%'], 'title' => ['修改', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'status'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //铝板材质类型
    public function quality2(){
        return $this->quality(5);
    }

    //新增铝卷材质类型
    public function qualityAdd()
    {

        $id = input('param.id');
        $type_pid = input('type_pid');
        // 获取数据
        $info = Db::name('wh_supplier_quality')->where(['id'=>$id])->find();
        if(empty($info['type_pid']))$info['type_pid'] = $type_pid;

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');

            // 验证失败 输出错误信息
            if(empty($data['title'])) $this->error('材质类型不能为空');

            if($id)$re = Db::name('wh_supplier_quality')->where(['id'=>$id])->update($data);
            else $re = Db::name('wh_supplier_quality')->insert($data);

            if ($re)$this->success('操作成功','','_parent_reload');
            else $this->error('操作失败');
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增')
            ->addHidden('type_pid')
            ->addFormItems([
                ['text:12||||must', 'title', '材质类型'],
            ])
            ->setFormData($info)
            //->layout(['title'=>12,'sort'=>12,])
            ->fetch();
    }
    //新增铝板材质类型
    public function qualityAdd2()
    {
        return $this->qualityAdd();
    }

}
